package com.bussanq.api.k8s.k8s;

import com.jfinal.aop.Inject;
import com.jfinal.kit.Kv;
import com.jfinal.template.Engine;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.api.model.PodBuilder;
import io.fabric8.kubernetes.api.model.PodList;
import io.fabric8.kubernetes.client.KubernetesClient;
import org.apache.log4j.Logger;

/**
 * Pod服务
 * @author lizh
 * @date 2019/9/14
 */
public class PodService {
	private static final Logger log = Logger.getLogger(PodService.class);

	@Inject
	K8sService k8sService;

	public Pod createPod(String nsName, String podName, String labelkey, String labelvalue, String containerName,
								String imageName){//, int cnPort
		Pod pod = new PodBuilder()
				.withApiVersion("v1")
				.withKind("Pod")
				.withNewMetadata()
				.withName(podName)
				.withNamespace(nsName)
				.addToLabels(labelkey, labelvalue)
				.endMetadata()
				.withNewSpec()
				.addNewContainer()
				.withName(containerName)
				.withImage(imageName)
//				.addNewPort()
//				.withContainerPort(cnPort)
//				.endPort()
				.endContainer()
				.endSpec()
				.build();
		KubernetesClient client = k8sService.getClient();
		try {
			//Pod 创建
//			client.pods().create(pod);
			String yml = "C:\\Users\\CJ\\Desktop\\spring.yml";
			Pod refreshed = client.pods().load(yml).create();
			client.pods().create(refreshed);
		//load(yml).createNew();
			System.out.println("pod create success");
		}catch (Exception e) {
			log.error(e);
			System.out.println("pod create failed");
		}
		return pod;
	}

	public String create(PodVo pod){
		String ym = Engine.use("k8sEngine").getTemplate("spring.yml").renderToString(Kv.by("image", pod.getImagename())
				.set("replicas",pod.getReplicas()));
		return k8sService.applyByStr(ym);
	}

	public String apply(){
		String ym = Engine.use("k8sEngine").getTemplate("spring.yml").renderToString(Kv.by("image", "httpd").set("replicas","2"));
		return k8sService.applyByStr(ym);
	}

	public String pod(){
		KubernetesClient client = k8sService.getClient();
		PodList list = client.pods().inNamespace("default").list();
		return list.getItems().get(0).getMetadata().getName();
	}
}
